package com.dancun.controller;


import com.dancun.entity.Course;
import com.dancun.entity.Student;
import com.dancun.entity.TDocument;
import com.dancun.service.ICourseService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-10-02
 */
@RestController

public class CourseController {
    @Autowired
    ICourseService courseService;

    @RequestMapping("/courselist")
    public ModelAndView list() {
        ModelAndView mav = new ModelAndView("/Main/Addcourse.jsp");
        List<Course> course = courseService.list();
        mav.addObject("list", course);
        return mav;
    }

    @RequestMapping("/listcoursejson")
    public String listCourse() throws IOException {
        List<Course> list = courseService.list();
        JSONArray jsonarray = new JSONArray();
        String[][] str = new String[list.size()][2];
//        response.setContentType("text/html;charset=utf-8");
//        PrintWriter out = response.getWriter();
        for (Course c : list) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("cid", c.getCid());
            jsonObject.put("cname", c.getCname());
            jsonarray.add(jsonObject);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("course", jsonarray);
//        out.print(jsonObject);
        return jsonObject.toString();
    }

    @RequestMapping("/Addcourse")
    public ModelAndView add(Course course) {
        ModelAndView mav = new ModelAndView("/courselist");
        if (courseService.save(course)) {
            mav.addObject("course", course);
            return mav;
        }

        mav.setViewName("/courselist");
        return mav;
    }

    @RequestMapping("/Updatecourse")
    public ModelAndView update(Course course) {
        ModelAndView mav = new ModelAndView("/courselist");
        if (courseService.updateById(course)) {
            return mav;
        }
        mav.setViewName("/courselist");
        return mav;
    }

    @RequestMapping("/delCourse")
    public String delete(@Param("id") String cid, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        if (courseService.removeById(cid)) {
            out.print("<script>alert('删除成功');window.location.href='courselist'</script>");
        } else {
            out.print("<script>alert('删除失败');window.location.href='courselist'</script>");
        }
        return null;

    }
}
